<?php
namespace app\home\controller;

use app\common\controller\Home;
use think\facade\Cache;
use think\facade\Db;
use think\facade\View;
use app\common\model\User;
//use Elliptic\EC;

class Index extends Home
{
    /*
     *  首页
     * */
    public function index()
    {
        return View::fetch();
    }

    public function profit()
    {
        $address = $this->request->get("address");
        $suffix = Db::name("config")->where("k","bonus_detail_table_num")->value("v");
        View::assign('suffix', $suffix);
        View::assign('address', $address);
        return View::fetch();
    }

    /*
     *  收益日志
     * */
    public function profitList(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            $post_suffix = $this->request->post("suffix","-1");
            $post_start_size = $this->request->post("start_size","0");
            $userModel = new User();
            $uid = $userModel->where("heco_address",$address)->value("id");
            if(empty($uid)){
                return $this->apiResponse(0,'fail');
            }
            $where = [];
            $where[] = ['uid','=', $uid];
            $suffix = Db::name("config")->where("k","bonus_detail_table_num")->value("v");
            $return_data = (new \app\common\controller\Common\CommonServer())->pageAction('bonus_detail_list', $where, $post_start_size, intval($post_suffix), $suffix,'id desc');

            $bonus_list = [];
            foreach ($return_data['list'] as $k => $v){
                $rate = getRate($v['lp'], $v['all_lp']);
                $rate = sprintf("%.6f",$rate);
                $bonus_list[] = [
                    'lp' => $v['lp'],
                    'rate' => $rate,
                    'token' => $v['token'].config("dbconfig.sys.b_token_name"),
                    'c_date' => date("Y-m-d H:i:s",$v['c_time'])
                ];
            }
            $return_data['list'] = $bonus_list;
            return $this->apiResponse(1,'success',$return_data);
        }
        return $this->apiResponse(0,'fail');
    }

    /*
     *  获取用户信息
     * */
    public function getWallet(){

        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            if(!checkWalletAddress($address)){
                return $this->apiResponse(0,'fail');
            }
            $user = new User();
            $user_id = $user::where('heco_address', $address)->value('id');
            $cache_key = md5('index_getWallet_login_'.$address);
            $is_change = Cache::get($cache_key);

            if(empty($user_id)){
                $res = $user->addUser([
                    'heco_address' => $address,
                    'c_time' => time(),
                    'login_time' => time(),
                    'login_date' => date("Ymd")
                ]);
                $user_id = $res['data'] ?? 0;
            }elseif(!$is_change){
                $user->where("id",$user_id)->update([
                    'login_time' => time(),
                    'login_date' => date("Ymd"),
                    'is_change_lp' => 0
                ]);
            }
            Cache::set($cache_key,1,600);
            if(empty($user_id)){
                return $this->apiResponse(0,'fail');
            }
//            $return_data = [
//                'plat_lp_wallet_address' => config("dbconfig.sys.plat_lp_wallet_address"),
//                'lp_contract_address' => config("dbconfig.sys.lp_contract_address"),
//            ];
            return $this->apiResponse(1,'success');
        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
     *  获取用户数据
     * */
    public function getPimLp(){

        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            if(!checkWalletAddress($address)){
                return $this->apiResponse(0,'fail');
            }
            $userServer = new \app\common\controller\User\UserServer();
            $res = $userServer->getPimLp($address);
            return $this->apiResponse(1,'success', $res);
        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
     *  当前可质押的LP余额
     * */
    public function lpBalance(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            $userServer = new \app\common\controller\User\UserServer();
            $balance = $userServer->lineLpBalance($address);
            return $this->apiResponse(1,'success', $balance);
        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
    *  当前可解押的LP余额
    * */
    public function lpBalance1(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            $userModel = new User();
            $lp_amount = $userModel->where("heco_address", $address)->value("lp_amount");
            $lp_amount = number_to_normal($lp_amount,6);
            return $this->apiResponse(1,'success', $lp_amount);
        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
     *  提取
     * */
    public function cash(){

        if($this->request->isAjax()){

            $address = $this->request->post("address",'');
            $token_num = $this->request->post("token_num",0);
            $token_num = bcdiv($token_num,1,6);
            $min_cash_num = config("dbconfig.sys.cash_min_num");
            if(!checkWalletAddress($address)){
                return $this->apiResponse(0,'请先连接钱包');
            }
            if($token_num <= 0 || $min_cash_num > $token_num){
                return $this->apiResponse(0,"最低提取金额为{$min_cash_num}");
            }
            $userModel = new User();
            $user_info = $userModel->where("heco_address", $address)->find();
            $balance = $user_info['token_amount'] ?? 0;
            if(empty($user_info['id']) || $balance < $token_num){
                return $this->apiResponse(0,'账户余额不足');
            }

            $cache_key = "index_cash_".$address;
            if(Cache::get($cache_key)){
                return $this->apiResponse(0,'提交中,请重复提交');
            }

            Cache::set($cache_key,1,300);
            $cashList = new \app\common\model\CashList();
            $cashList->startTrans();
            try{
                $cash_id = $cashList->insertGetId([
                    'uid' => $user_info['id'],
                    'wallet_address' => $address,
                    'token_money' => $token_num,
                    'c_time' => time(),
                ]);
                if(empty($cash_id)){
                    $cashList->rollback();
                    Cache::delete($cache_key);
                    return $this->apiResponse(0,'提取失败');
                }
                $userServer = new \app\common\controller\User\UserServer();
                $fund_res = $userServer->fundLog([
                    'uid' => $user_info['id'],
                    'money' => -1 * $token_num,
                    'type' => 2,
                    'detail' => '提取',
                    'note' => $cash_id,
                ]);
                if($fund_res['code'] != 1){
                    $cashList->rollback();
                    Cache::delete($cache_key);
                    return $this->apiResponse(0, $fund_res['msg']);
                }
                $txid = $userServer->tranfersAction($address, $token_num);
                if(empty($txid)){
                    $cashList->rollback();
                    Cache::delete($cache_key);
                    return $this->apiResponse(0,'提取失败[1]');
                }
                $cashList->where("id",$cash_id)->update([
                    'trade_hash' => $txid,
                ]);
                $cashList->commit();
                Cache::delete($cache_key);
                return $this->apiResponse(1,'提取成功');
            }catch (\Exception $e){
                $cashList->rollback();
                Cache::delete($cache_key);
                return $this->apiResponse(0,'提取失败[err]');
            }
        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
     *  质押检查
     * */
    public function checkPledgeData(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            $lp_num = $this->request->post("lp_num",0);
            $lp_num = bcdiv($lp_num,1,6);
            if(!checkWalletAddress($address)){
                return $this->apiResponse(0,'请先连接钱包');
            }

            $min_pledge_num = config("dbconfig.sys.min_pledge_num");

            if($lp_num <= 0 || $min_pledge_num > $lp_num){

                return $this->apiResponse(0,"最低质押数量为{$min_pledge_num}");
            }

            $userModel = new User();
            $uid = $userModel->where("heco_address", $address)->value("id");

            if(empty($uid)){
                return $this->apiResponse(0,'请先连接钱包');
            }

            $lp_contract_address = config("dbconfig.sys.lp_contract_address");
            $decimal = (new \Heco())->contractDecimal($lp_contract_address);

            $return_data = [
                'plat_lp_wallet_address' => config("dbconfig.sys.plat_lp_wallet_address"),
                'lp_contract_address' => $lp_contract_address,
                'amount' => bcmul($lp_num, bcpow(10, $decimal), 0),
                'lp_num' => $lp_num,
            ];
            return $this->apiResponse(1,'success',$return_data);

        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
     *  质押
     * */
    public function pledgeAction(){

        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            $lp_num = $this->request->post("lp_num",0);
            $txid = $this->request->post("txid",'');
            $cache_key = "index_pledgeAction_".$address;
            if(Cache::get($cache_key)){
                return $this->apiResponse(0,'提交中,请重复提交');
            }
            Cache::set($cache_key,1,300);
            if(empty($txid)){
                Cache::delete($cache_key);
                return $this->apiResponse(0,'失败');
            }
            $lp_num = bcdiv($lp_num,1,6);
            if($lp_num <= 0){
                Cache::delete($cache_key);
                return $this->apiResponse(0,"失败[amount]");
            }
            $plat_lp_wallet_address = config("dbconfig.sys.plat_lp_wallet_address");
            $userModel = new User();
            $uid = $userModel->where("heco_address", $address)->value("id");
            $uid = intval($uid);

            $cashList = new \app\common\model\LpCashList();
            if($cashList->where('trade_hash', $txid)->count()){
                Cache::delete($cache_key);
                return $this->apiResponse(0,'失败');
            }
            $cashList->startTrans();
            try{
                $cash_id = $cashList->insertGetId([
                    'uid' => $uid,
                    'type' => 1,
                    'from_address' => $address,
                    'to_address' => $plat_lp_wallet_address,
                    'money' => $lp_num,
                    'trade_hash' => $txid,
                    'c_time' => time(),
                ]);
                if(empty($cash_id)){
                    $cashList->rollback();
                    Cache::delete($cache_key);
                    return $this->apiResponse(0,'质押失败[1]');
                }
                $cashList->commit();
                Cache::delete($cache_key);
                return $this->apiResponse(1,'质押成功');
            }catch (\Exception $e){
                $cashList->rollback();
                Cache::delete($cache_key);
                return $this->apiResponse(0,'质押失败[err]');
            }
        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
     *  解押
     * */
    public function relePledgeAction(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            $lp_num = $this->request->post("lp_num",0);
            if(!checkWalletAddress($address)){
                return $this->apiResponse(0,'请先连接钱包');
            }
            if(!session($address)){
                return $this->apiResponse(0,'解押失败，您无此权限');
            }
            $min_rele_pledge_num = config("dbconfig.sys.min_rele_pledge_num");
            $lp_num = bcdiv($lp_num,1,6);
            if($lp_num <= 0 || $min_rele_pledge_num > $lp_num){
                return $this->apiResponse(0,"最低解押数量为{$min_rele_pledge_num}");
            }
            $userModel = new User();
            $uid = $userModel->where("heco_address", $address)->value("id");
            if(empty($uid)){
                return $this->apiResponse(0,'请先连接钱包');
            }
            $plat_lp_wallet_address = config("dbconfig.sys.plat_lp_wallet_address");
            $plat_lp_wallet_private = config("dbconfig.sys.plat_lp_wallet_private");
            $lp_contract_address = config("dbconfig.sys.lp_contract_address");
            if(empty($plat_lp_wallet_address) ||empty($plat_lp_wallet_private)){
                return $this->apiResponse(0,'解押失败[2]');
            }
            $userModel = new User();
            $user_info = $userModel->where("heco_address", $address)->find();
            $balance = $user_info['lp_amount'] ?? 0;
            if(empty($user_info['id']) || $balance < $lp_num){
                return $this->apiResponse(0,'账户LP余额不足');
            }

            $cache_key = "index_relePledgeAction_".$address;
            if(Cache::get($cache_key)){
                return $this->apiResponse(0,'提交中,请重复提交');
            }
            Cache::set($cache_key,1,300);

            $cashList = new \app\common\model\LpCashList();
            $cashList->startTrans();
            try{
                $cash_id = $cashList->insertGetId([
                    'uid' => $user_info['id'],
                    'type' => 2,
                    'from_address' => $plat_lp_wallet_address,
                    'to_address' => $address,
                    'money' => $lp_num,
                    'c_time' => time(),
                ]);
                if(empty($cash_id)){
                    $cashList->rollback();
                    Cache::delete($cache_key);
                    return $this->apiResponse(0,'解押失败');
                }

                $lpFundLog = new \app\common\model\LpFundLog();
                $fund_res = $lpFundLog->addFundLog([
                    'uid' => $user_info['id'],
                    'money' => -1 * $lp_num,
                    'type' => 2,
                    'detail' => '解押',
                    'note' => $cash_id,
                ]);
                if($fund_res['code'] != 1){
                    $cashList->rollback();
                    Cache::delete($cache_key);
                    return $this->apiResponse(0, $fund_res['msg']);
                }
                $heco = new \Heco();
                $txid = $heco->contractTranfer($plat_lp_wallet_address, $lp_num, $lp_contract_address, $plat_lp_wallet_private, $address);
                if(empty($txid)){
                    $cashList->rollback();
                    Cache::delete($cache_key);
                    return $this->apiResponse(0,'解押失败[1]');
                }
                $cashList->where("id",$cash_id)->update([
                    'trade_hash' => $txid,
                ]);
                $cashList->commit();
                Cache::delete($cache_key);
                return $this->apiResponse(1,'解押成功');
            }catch (\Exception $e){
                $cashList->rollback();
                Cache::delete($cache_key);
                return $this->apiResponse(0,'解押失败[err]');
            }
        }
        return $this->apiResponse(0,'路由错误');
    }

    /*
     * 实时更新用户LP余额
     * */
    public function changeLpBalance(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            if(!checkWalletAddress($address)){
                return $this->apiResponse(0,'');
            }
            $userModel = new User();
            $uid = $userModel->where("heco_address", $address)->value("id");
            $userServer = new \app\common\controller\User\UserServer();
            if(!empty($uid) && $userServer->lpBalance($uid)){
                $user_info = $userModel->find($uid);
                $lp_amount = $user_info['lp_amount'];
                $all_lp_amount = $userModel->sumLP();
                $lp_rate = getRate($lp_amount, $all_lp_amount);
                $return_data = [
                    'lp_amount' => sprintf("%.6f", $lp_amount),
                    'all_lp_amount' => sprintf("%.6f", $all_lp_amount),
                    'lp_rate' => sprintf("%.6f", $lp_rate),
                ];
                return $this->apiResponse(1,'success',$return_data);
            }
            return $this->apiResponse(0,'');
        }
        return $this->apiResponse(0,'路由错误');
    }

    public function isLogin(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            if(session($address)){
                return $this->apiResponse(1,'success');
            }
            $sign_msg = md5(time().'bacc');
            session('sign_msg', $sign_msg);
            return $this->apiResponse(0,'', $sign_msg);
        }
        return $this->apiResponse(0,'路由错误');
    }

    public function accountVerify(){
        if($this->request->isAjax()){
            $address = $this->request->post("address",'');
            $sign_msg = $this->request->post("sign_msg",'');
            $signature = $this->request->post("signature",'');
            if(strlen($address) < 10 || empty($sign_msg) || empty($signature)){
                return $this->apiResponse(0,'fail');
            }
            if($sign_msg != session('sign_msg')){
                return $this->apiResponse(0,'fail');
            }
            $heco = new \Heco();
            if($heco->verify_sign($sign_msg, $signature, $address)){
                session('sign_msg','');
                session($address,1);
                return $this->apiResponse(1,'success');
            }
            return $this->apiResponse(0,'fail');
        }
        return $this->apiResponse(0,'路由错误');
    }



}